package java_thinking.unit_21._21_4;

import net.jcip.annotations.ThreadSafe;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Desc:   4-12    安全发布底层状态的车辆追踪器 Point
 * @author: cww
 * @DateTime: 2019/6/3 18:49
 */
@ThreadSafe
public class PublishingVehicleTracker {
    private final Map<String, SafePoint> locations;
    private final Map<String, SafePoint> unmodifiableMap;

    public PublishingVehicleTracker(Map<String, SafePoint> locations) {
        this.locations = new ConcurrentHashMap<>(locations);
        this.unmodifiableMap = Collections.unmodifiableMap(this.locations);
    }

    /**
     * 返回不可变的副本
     * @return
     */
    public Map<String, SafePoint> getLocations() {
        return unmodifiableMap;
    }

    /**
     * 可以通过修改返回的 SafePoint 来改变车辆位置
     * @param id
     * @return
     */
    public SafePoint getLocation(String id) {
        return locations.get(id);
    }

    public void setLocation(String id, int x, int y) {
        if (!locations.containsKey(id)) {
            throw new IllegalArgumentException("invalid vehicle name: " + id);
        }
        locations.get(id).set(x, y);
    }
}
